<template>
  <view class="seller-comment-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="onBack">
        <uni-icons type="arrowleft" size="48rpx"></uni-icons>
      </view>
      <view class="header-title">卖家服务评价</view>
    </view>

    <!-- 评价表单 -->
    <view class="comment-form">
      <!-- 订单信息 -->
      <view class="order-info">
        <view class="order-header">
          <text class="seller-name">{{ orderInfo.sellerName || '卖家名称' }}</text>
          <text class="order-id">订单号: {{ orderInfo.orderNumber || '订单编号' }}</text>
        </view>
        <view class="order-goods">
          <image
              class="goods-image"
              :src="orderInfo.itemImage"
              mode="aspectFill"
          ></image>
          <view class="goods-detail">
            <view class="goods-name">{{ orderInfo.itemName || '商品名称' }}</view>
            <view class="goods-spec">{{ orderInfo.description || '规格信息' }}</view>
            <view class="goods-price">¥{{ orderInfo.totalAmount || 0 }}</view>
          </view>
        </view>
      </view>

      <!-- 评分维度 -->
      <view class="rating-dimensions">
        <!-- 信用评分 -->
        <view class="rating-item">
          <view class="rating-header">
            <text class="rating-label">卖家信用</text>
            <text class="rating-text">{{ getRatingText(creditRating) }}</text>
          </view>
          <view class="star-container">
            <uni-icons
                v-for="(item, index) in 5"
                :key="index"
                :type="index < creditRating ? 'star-filled' : 'star'"
                :color="index < creditRating ? '#ffd161' : '#ccc'"
                size="48rpx"
                @click="setRating('creditRating', index + 1)"
            ></uni-icons>
          </view>
        </view>

        <!-- 发货速度评分 -->
        <view class="rating-item">
          <view class="rating-header">
            <text class="rating-label">发货速度</text>
            <text class="rating-text">{{ getRatingText(speedRating) }}</text>
          </view>
          <view class="star-container">
            <uni-icons
                v-for="(item, index) in 5"
                :key="index"
                :type="index < speedRating ? 'star-filled' : 'star'"
                :color="index < speedRating ? '#ffd161' : '#ccc'"
                size="48rpx"
                @click="setRating('speedRating', index + 1)"
            ></uni-icons>
          </view>
        </view>

        <!-- 服务态度评分 -->
        <view class="rating-item">
          <view class="rating-header">
            <text class="rating-label">服务态度</text>
            <text class="rating-text">{{ getRatingText(serviceRating) }}</text>
          </view>
          <view class="star-container">
            <uni-icons
                v-for="(item, index) in 5"
                :key="index"
                :type="index < serviceRating ? 'star-filled' : 'star'"
                :color="index < serviceRating ? '#ffd161' : '#ccc'"
                size="48rpx"
                @click="setRating('serviceRating', index + 1)"
            ></uni-icons>
          </view>
        </view>
      </view>

      <!-- 评价内容 -->
      <view class="comment-content">
        <text class="content-label">评价内容</text>
        <textarea
            class="content-input"
            v-model="comment"
            placeholder="请分享您对卖家服务的体验，帮助其他用户做出决策..."
            maxlength="500"
            auto-height
        ></textarea>
        <text class="content-count">{{ comment.length }}/500</text>
      </view>

      <!-- 匿名选项 -->
      <view class="anonymous-option">
        <uni-checkbox-group v-model="anonymous">
          <label class="checkbox-label">
            <uni-checkbox name="anonymous" :style="{transform: 'scale(0.8)'}"></uni-checkbox>
            <text>匿名评价</text>
          </label>
        </uni-checkbox-group>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitComment">
      <text>提交评价</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted} from 'vue';
import { request } from '@/utils/request';
import { selectOrder ,addComment} from '@/apis/orderApi';
import { onLoad } from '@dcloudio/uni-app';
// 获取页面参数
const userInfo = uni.getStorageSync('userInfo') || {};
const orderInfo = ref({
  orderId: '',
  orderNumber: '',
  productTitle: '',
  totalAmount: '',
  orderPrice: '',
  userId: '',
  nickName: '',
  itemName: '',
  itemImage: '',
  description: ''
});

// 评价表单数据
const sellerInfo = ref({});
// 三个维度的评分
const creditRating = ref(5);   // 卖家信用
const speedRating = ref(5);    // 发货速度
const serviceRating = ref(5);  // 服务态度

const comment = ref('');
const anonymous = ref([]); // 匿名选项

// 是否为编辑已有评价
const isEditing = ref(false);

onLoad((options) => {
  console.log('页面加载参数:', options); // 调试信息,{orderId:54}
  if (options.orderId) {
    orderInfo.value.orderId = options.orderId;
    // 并行获取订单信息和倒计时
    Promise.all([
      fetchOrderInfo(options.orderId),
    ]).catch(error => {
      console.error('页面加载失败:', error);
    });
  }
});

// 获取订单信息
const fetchOrderInfo = async (orderId) => {
  try {
    const res = await selectOrder(orderId);
    if (res.data.code === 200) {
      orderInfo.value = res.data.data;
      console.log("商品信息", orderInfo.value);

      // 检查订单是否已有评价
      if (orderInfo.value.comment) {
        try {
          // 解析JSON格式的评价信息
          const commentInfo = JSON.parse(orderInfo.value.comment);
          creditRating.value = commentInfo.creditRating || 5;
          speedRating.value = commentInfo.speedRating || 5;
          serviceRating.value = commentInfo.serviceRating || 5;
          comment.value = commentInfo.content || '';
          anonymous.value = commentInfo.anonymous ? ['anonymous'] : [];
          isEditing.value = true;
          console.log('已加载已有评价信息');
        } catch (e) {
          console.error('解析评价信息失败:', e);
        }
      }
    }
  } catch (err) {
    console.error('获取订单信息失败:', err);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};

// 设置评分
const setRating = (ratingType, value) => {
  if (ratingType === 'creditRating') {
    creditRating.value = value;
  } else if (ratingType === 'speedRating') {
    speedRating.value = value;
  } else if (ratingType === 'serviceRating') {
    serviceRating.value = value;
  }
};

// 获取评分文本
const getRatingText = (rating) => {
  const ratingTexts = ['非常差', '差', '一般', '好', '非常好'];
  return ratingTexts[rating - 1] || '非常好';
};

// 返回上一页
const onBack = () => {
  uni.navigateBack();
};

// 提交评价
const submitComment = async () => {
  // 表单验证
  if (creditRating.value < 1 || speedRating.value < 1 || serviceRating.value < 1) {
    return uni.showToast({ title: '请完成所有评分', icon: 'none' });
  }

  if (!comment.value.trim()) {
    return uni.showToast({ title: '请输入评价内容', icon: 'none' });
  }

  // 显示加载中
  uni.showLoading({ title: '提交中...', mask: true });

  try {
    // 构建评价数据对象
    const commentInfo = {
      creditRating: creditRating.value,
      speedRating: speedRating.value,
      serviceRating: serviceRating.value,
      content: comment.value,
      anonymous: anonymous.value.includes('anonymous')
    };

    // 提交评价数据（直接发送commentInfo对象，让axios自动序列化为JSON）
    // const res = await request({
    //   url: `/api/orders/${orderInfo.value.orderId}/seller-comment`,
    //   method: 'POST',
    //   data: commentInfo
    // });
    const commentJson = JSON.stringify(commentInfo);
    const encodedComment = encodeURIComponent(commentJson);
    const res = await addComment(orderInfo.value.orderId, encodedComment)

    if (res.data.code === 200) {
      uni.hideLoading();
      uni.showToast({ title: '评价提交成功', icon: 'success' });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.hideLoading();
      uni.showToast({ title: res.data.msg || '提交失败', icon: 'none' });
    }
  } catch (err) {
    console.error('提交评价失败:', err);
    uni.hideLoading();
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};
</script>
<style scoped>
/* 样式变量 */
:root {
  --primary-color: #ff4d4f;
  --border-color: #f5f5f5;
  --text-primary: #333;
  --text-secondary: #666;
  --text-tertiary: #999;
  --gap-sm: 16rpx;
  --gap-md: 32rpx;
  --radius: 16rpx;
}

.seller-comment-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-size: 28rpx;
}

/* 头部导航 */
.header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 96rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  position: absolute;
  left: var(--gap-md);
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 36rpx;
  color: var(--text-primary);
  font-weight: 500;
}

/* 评价表单 */
.comment-form {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 var(--gap-md);
}

/* 订单信息 */
.order-info {
  padding: 24rpx 0;
  border-bottom: 2rpx solid var(--border-color);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.seller-name {
  font-size: 32rpx;
  color: var(--text-primary);
  font-weight: 500;
}

.order-id {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.order-goods {
  display: flex;
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
  background-color: #f5f5f5;
}

.goods-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: var(--text-primary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-spec {
  font-size: 24rpx;
  color: var(--text-tertiary);
  margin-top: 8rpx;
}

.goods-price {
  font-size: 28rpx;
  color: var(--primary-color);
  margin-top: 8rpx;
}

/* 评分维度 */
.rating-dimensions {
  padding: 24rpx 0;
}

.rating-item {
  margin-bottom: 32rpx;
}

.rating-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.rating-label {
  font-size: 28rpx;
  color: var(--text-primary);
}

.rating-text {
  font-size: 28rpx;
  color: var(--text-secondary);
}

.star-container {
  display: flex;
  gap: 24rpx;
}

/* 评价内容 */
.comment-content {
  padding: 24rpx 0;
  border-top: 2rpx solid var(--border-color);
}

.content-label {
  font-size: 28rpx;
  color: var(--text-primary);
  margin-bottom: 16rpx;
  display: block;
}

.content-input {
  width: 100%;
  min-height: 200rpx;
  padding: 16rpx;
  box-sizing: border-box;
  border: 2rpx solid var(--border-color);
  border-radius: 8rpx;
  font-size: 28rpx;
  color: var(--text-primary);
}

.content-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: var(--text-tertiary);
  margin-top: 12rpx;
}

/* 匿名选项 */
.anonymous-option {
  padding: 24rpx 0;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

/* 提交按钮 */
.submit-btn {
  width: 680rpx;
  height: 88rpx;
  background-color: var(--primary-color);
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 60rpx auto;
}
</style>